package com.siemens.industrial.web.mvc.service.admin;

import com.siemens.industrial.model.admin.Service;
import com.siemens.industrial.web.mvc.dao.admin.ServiceDao;
import com.siemens.industrial.web.mvc.pojo.DataTableQuery;
import com.siemens.industrial.web.mvc.pojo.TenantServiceItem;
import org.springframework.jdbc.core.JdbcTemplate;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by qupen on 2016/9/21.
 */
@org.springframework.stereotype.Service
public class ServeService {
    @Resource
    ServiceDao serviceDao;

    @Resource
    JdbcTemplate jdbcTemplate;

    public List<Service> getServiceList() {
        return serviceDao.getServices();
    }

    public List<TenantServiceItem> getServiceManageList() {
        return serviceDao.getTenantServiceList();
    }

    public  Map<String, Object> getManageCount(){
        List<Map<String,Object>> deviceCountOfService = serviceDao.getServerStatistics();
        List<Map<String,Object>> deviceCountOfTenant = serviceDao.getDeviceCountOfTenant();
        return new HashMap<String,Object>() {{
            put("deviceCountOfService", deviceCountOfService);
            put("deviceCountOfTenant", deviceCountOfTenant);
        }};
    }

    public boolean setServiceEnabled(String serviceId,int enabled){
       return serviceDao.updateEnabled(serviceId,enabled)==1;
    }

    //dataTable search service manage list
    public Map<String,Object> getServiceManageListByDataTable(HttpServletRequest request){
        DataTableQuery dt = new DataTableQuery(request);
        List<Map<String, Object>> list = new ArrayList<>();

        String sql ="select dt.tenant_id,dt.serviceId,dt.valid,dt.enabled,dt.tenant_name,dt.serviceName,dt.count from (\n " +
                "SELECT \n" +
                "    a.tenant_id,\n" +
                "    a.tenant_name,\n" +
                "    GROUP_CONCAT(b.service_id) serviceId,\n" +
                "    GROUP_CONCAT(CONCAT(b.start_date, ' - ', b.end_date)) valid,\n" +
                "    GROUP_CONCAT(b.end_date) endDate,\n" +
                "    GROUP_CONCAT(c.enabled) enabled,\n" +
                "    GROUP_CONCAT(c.service_name) serviceName,\n" +
                "    IFNULL(d.count, 0) `count`\n" +
                "FROM\n" +
                "    siemens.tenant a\n" +
                "        LEFT JOIN\n" +
                "    siemens.tenant_service_relation b ON a.tenant_id = b.tenant_id\n" +
                "        LEFT JOIN\n" +
                "    `siemens`.`service` c ON b.service_id = c.service_id\n" +
                "        LEFT JOIN\n" +
                "    (SELECT \n" +
                "        tenant_id, COUNT(1) `count`\n" +
                "    FROM\n" +
                "        siemens.device\n" +
                "    GROUP BY tenant_id) d ON a.tenant_id = d.tenant_id\n" +
                "GROUP BY a.tenant_id) dt where 1=1\n";
        int total = jdbcTemplate.queryForList(sql).size();
        int filteredCount = total;
        if (!dt.getSearch().equals("")) {
            String search = " and (dt.tenant_id like '%" + dt.getSearch() + "%' or dt.valid like '%" + dt.getSearch() + "%' or dt.enabled like '%" + dt.getSearch() + "%' or dt.tenant_name like '%" + dt.getSearch() + "%' or dt.serviceName like '%" + dt.getSearch() + "%' or dt.count like '%" + dt.getSearch() + "%')";
            sql += search;
            filteredCount = jdbcTemplate.queryForList(sql + search).size();
        }

        if (!dt.getOrderDBColumn().equals("") && !dt.getOrderAscOrDesc().equals("")) {
            String order = " ORDER BY `" + dt.getOrderDBColumn() + "` " + dt.getOrderAscOrDesc();
            sql += order;
        }

        String limit = " limit " + dt.getStart() + "," + dt.getLength();
        sql += limit;

        list = jdbcTemplate.queryForList(sql);
        return dt.buildResponse(filteredCount, total, list);
    }

    //dataTable search service list
    public Map<String,Object> getServiceListByDataTable(HttpServletRequest request) {
        DataTableQuery dt = new DataTableQuery(request);
        List<Map<String, Object>> list = new ArrayList<>();

        String totalSql = "SELECT COUNT(1) FROM `siemens`.`service` WHERE 1=1\n";
        String sql = "SELECT * FROM `siemens`.`service` WHERE 1=1\n";
        int total = jdbcTemplate.queryForObject(totalSql, Integer.class);
        int filteredCount = total;
        if (!dt.getSearch().equals("")) {
            String search = " and (`service_name`like '%" + dt.getSearch() + "%' or `service_desc` like '%" + dt.getSearch() + "%' or `enabled` like '%" + dt.getSearch() + "%' or `service_id` like '%" + dt.getSearch() + "%')";
            sql += search;
            filteredCount = jdbcTemplate.queryForObject(totalSql + search, Integer.class);
        }

        if (!dt.getOrderDBColumn().equals("") && !dt.getOrderAscOrDesc().equals("")) {
            String order = " ORDER BY `" + dt.getOrderDBColumn() + "` " + dt.getOrderAscOrDesc();
            sql += order;
        }

        String limit = " limit " + dt.getStart() + "," + dt.getLength();
        sql += limit;

        list = jdbcTemplate.queryForList(sql);
        return dt.buildResponse(filteredCount, total, list);
    }

    public void save(Service service) {
        Service serviceDB = serviceDao.findOneById(service.getService_id());
        if (serviceDB == null) {
            serviceDao.save(service);
        } else {
            serviceDB.setService_name(service.getService_name());
            serviceDB.setService_desc(service.getService_desc());
            serviceDB.setEnabled(service.getEnabled());
            serviceDao.update(serviceDB);
        }
    }
}
